package com.shenghua.controller;

import com.alibaba.fastjson.JSON;
import com.shenghua.dao.mapper.LimitsMapper;
import com.shenghua.dao.model.Limits;
import com.shenghua.dao.model.LimitsExample;
import com.shenghua.dao.model.User;
import com.shenghua.service.LimitsService;
import com.shenghua.utils.ListUtils;
import com.shenghua.utils.StringUtils;
import com.shenghua.utils.beans.Constants;
import com.shenghua.utils.beans.Dto;
import com.shenghua.utils.beans.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Console;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/3/17.
 */
@Controller
@RequestMapping("/")
public class LimitsController {
    Logger logger = LoggerFactory.getLogger(LimitsController.class);

    @Autowired
    private LimitsMapper limitsMapper;
    @Resource
    private LimitsService limitsService;

    // 权限管理页面
    @RequestMapping(value = "/limitsManager/normal")
    public String limitsManagerPage_Normal() {
        return "pc/limits/limitsManager";
    }
    // 新增权限页面
    @RequestMapping(value = "/addLimits/normal/{id}")
    public String addLimitsPage_Normal(
            @PathVariable(name = "id") Integer id,
            HttpServletRequest request, Model model) {
        logger.info("[LimitsController] addLimitsPage_Normal parentCode={}", id);
        model.addAttribute("id", id);// 父级编号
        return "pc/limits/addLimits";
    }
    // 编辑权限页面
    @RequestMapping(value = "/editLimits/normal/{id}")
    public String editLimitsPage_Normal(
            @PathVariable(name = "id") Integer id,
            HttpServletRequest request, Model model) {
        logger.info("[LimitsController] editLimitsPage_Normal id={}", id);
        LimitsExample limitsExample = new LimitsExample();
        LimitsExample.Criteria criteria = limitsExample.createCriteria();
        criteria.andIdEqualTo(id);
        List<Limits> limitsList = limitsMapper.selectByExample(limitsExample);
        if(ListUtils.isEmpty(limitsList)) {
            logger.error("[LimitsController] editLimitsPage_Normal 权限不存在！");
            return "pc/limits/limitsManager";
        }
        Limits limits = limitsList.get(0);
        model.addAttribute("limits", limits);// 当前编辑的权限信息
        return "pc/limits/editLimits";
    }

    //查询权限信息
    @RequestMapping(value = "/findLimitsByParentCode/{pcode}", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String findLimitsByParentCode(@PathVariable String pcode) {
        System.out.println("[LimitsController] findLimitsByParentCode 父编号parentCode:"+pcode);
        Dto<Map<String, Object>> dto = new Dto<>();
        if(StringUtils.isBlank(pcode)) {
            dto.ReturnFail(null, ErrorCode.LIMITS_Query_FAIL);
            return JSON.toJSONString(dto);
        }
        LimitsExample example = new LimitsExample();
        LimitsExample.Criteria criteria = example.createCriteria();
        Limits pLimit = null;
        if (Constants.PARENTCODE_MINUS.equals(pcode)) {
            criteria.andParentCodeEqualTo(-1);
        } else {
            criteria.andParentCodeEqualTo(Integer.parseInt(pcode));// 查找子权限
            LimitsExample example1 = new LimitsExample();
            LimitsExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andLimitCodeEqualTo(Integer.parseInt(pcode));// 查找父权限自己
            List<Limits> pLimits = limitsMapper.selectByExample(example1);
            if(ListUtils.isNotEmpty(pLimits)) {
                pLimit = pLimits.get(0);
            }
        }
        List<Limits> limitsList = limitsMapper.selectByExample(example);
        if(ListUtils.isNotEmpty(limitsList) && null != pLimit) {
            StringBuilder sb = new StringBuilder();
            for (Limits l : limitsList) {
                sb.append(l.getId().toString()).append(",");
            }
            String s = sb.toString();
            s = s.substring(0, s.length()-1);
            pLimit.setDescribed(s);
            //limitsList.add(pLimit);
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("data", limitsList);
        dto.ReturnSuccess(paramMap, ErrorCode.LIMITS_Query_SUCCESS);
        return JSON.toJSONString(dto);
    }

    // 新增权限信息
    @RequestMapping(value = "/addNewLimit/normal", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String addNewLimit_Normal(Limits limits, HttpServletRequest request) {
        Dto<Limits> dto = new Dto<>();
        User user = (User) request.getSession().getAttribute("userSession");
        if (null == user) {
            logger.debug("[LimitsController] addNewLimit_Normal 用户未登录");
            dto.ReturnFail(new Limits(), ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        if (null == limits) {
            logger.info("[LimitsController] addNewLimit_Normal 参数不能为空");
            dto.ReturnFail(new Limits(), ErrorCode.PARAMETER_IS_NULL);
            return JSON.toJSONString(dto);
        }
        logger.info("[LimitsController] addNewLimit_Normal 新增权限信息：" + JSON.toJSONString(limits));
        limits.setCreated(new Date());
        limits.setCreateUserid(user.getId().toString());
        limits.setCreateNickname(user.getNickname());

        dto = limitsService.addNewLimits(limits);
        return JSON.toJSONString(dto);
    }

    // 编辑权限信息
    @RequestMapping(value = "/editCurrentLimit/normal", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String editCurrentLimit_Normal(Limits limits, HttpServletRequest request) {
        Dto<Limits> dto = new Dto<>();
        User user = (User) request.getSession().getAttribute("userSession");
        if (null == user) {
            logger.debug("[LimitsController] editCurrentLimit_Normal 用户未登录");
            dto.ReturnFail(new Limits(), ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        if (null == limits) {
            logger.info("[LimitsController] editCurrentLimit_Normal 参数不能为空");
            dto.ReturnFail(new Limits(), ErrorCode.PARAMETER_IS_NULL);
            return JSON.toJSONString(dto);
        }
        logger.info("[LimitsController] editCurrentLimit_Normal 编辑权限信息：" + JSON.toJSONString(limits));
        limits.setUpdated(new Date());
        limits.setUpdateUserid(user.getId().toString());
        limits.setUpdateNickname(user.getNickname());

        dto = limitsService.editCurrentLimits(limits);
        return JSON.toJSONString(dto);
    }


    // 是否允许删除权限
    @RequestMapping(value = "/toDeleteLimits/normal/{id}")
    @ResponseBody
    public String toDeleteLimits_Normal(
            @PathVariable(name = "id") Integer id) {
        Dto<Limits> dto = new Dto<>();
        logger.info("[LimitsController] toDeleteLimits_Normal limitCode={}", id);
        LimitsExample limitsExample = new LimitsExample();
        LimitsExample.Criteria criteria = limitsExample.createCriteria();
        criteria.andParentCodeEqualTo(id);
        List<Limits> limitsList = limitsMapper.selectByExample(limitsExample);
        if(ListUtils.isNotEmpty(limitsList)) {
            logger.error("[LimitsController] toDeleteLimits_Normal 权限属于父级权限，不允许删除！");
            dto.ReturnFail(limitsList.get(0), ErrorCode.LIMITS_NOT_ALLOW_DELETE);
            return JSON.toJSONString(dto);
        }
        dto.ReturnSuccess(new Limits(), ErrorCode.LIMITS_ALLOW_DELETE);
        return JSON.toJSONString(dto);
    }

    // 删除权限信息
    @RequestMapping(value = "/deleteLimits/normal/{id}", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String deleteLimits_Normal(@PathVariable(name = "id") Integer id,
                                      HttpServletRequest request) {
        Dto<Limits> dto = new Dto<>();
        User user = (User) request.getSession().getAttribute("userSession");
        if (null == user) {
            logger.debug("[LimitsController] deleteLimits_Normal 用户未登录");
            dto.ReturnFail(new Limits(), ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        LimitsExample limitsExample = new LimitsExample();
        LimitsExample.Criteria criteria = limitsExample.createCriteria();
        criteria.andParentCodeEqualTo(id);
        List<Limits> limitsList = limitsMapper.selectByExample(limitsExample);
        if(ListUtils.isNotEmpty(limitsList)) {
            logger.error("[LimitsController] deleteLimits_Normal 权限属于父级权限，不允许删除！");
            dto.ReturnFail(new Limits(), ErrorCode.LIMITS_NOT_ALLOW_DELETE);
            return JSON.toJSONString(dto);
        }
        LimitsExample limitsExample1 = new LimitsExample();
        LimitsExample.Criteria criteria1 = limitsExample1.createCriteria();
        criteria1.andLimitCodeEqualTo(id);
        List<Limits> limitsList1 = limitsMapper.selectByExample(limitsExample1);
        if(ListUtils.isEmpty(limitsList1)) {
            logger.error("[LimitsController] deleteLimits_Normal 权限不存在，删除失败！");
            dto.ReturnFail(new Limits(), ErrorCode.LIMITS_DELETE_FAIL);
            return JSON.toJSONString(dto);
        }
        Limits limits = limitsList1.get(0);
        if(limits.getParentCode() == -1) {
            logger.error("[LimitsController] deleteLimits_Normal 权限属于顶级权限，不允许删除！");
            dto.ReturnFail(new Limits(), ErrorCode.LIMITS_NOT_ALLOW_DELETE);
            return JSON.toJSONString(dto);
        }
        int i = limitsMapper.deleteByPrimaryKey(limits.getId());
        if(!(i>0)) {
            logger.error("[LimitsController] deleteLimits_Normal 权限删除失败！");
            dto.ReturnFail(new Limits(), ErrorCode.LIMITS_DELETE_FAIL);
            return JSON.toJSONString(dto);
        }
        // 删除role_limit中的相关信息
        logger.error("[LimitsController] deleteLimits_Normal 权限删除成功！");
        dto.ReturnSuccess(limits, ErrorCode.LIMITS_DELETE_SUCCESS);
        return JSON.toJSONString(dto);
    }

}
